package com.lzx.iteam.provider;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.lzx.iteam.bean.aidl.ChatMoreMsg;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by hfx on 15/2/12.
 */
public class MessageDB {
    private static final String DB_NAME = "message.db";
    private SQLiteDatabase mDb;
    //message 表相关字段
    private static final String SENDER_ID = "sender_id";
    private static final String MSG_ID = "msg_id";
    private static final String SENDER_NAME = "sender_name";
    private static final String SENDER_IMG = "sender_img";
    private static final String SEND_TIME = "send_time";
    private static final String IS_READED = "is_readed";
    private static final String TEXT_CONTENT = "text_content";
    private static final String IMG_CONTENT = "img_content";
    private static final String IMG_THUMBNAILS = "img_thumbnails";
    private static final String VOICE_CONTENT = "voice_content";
    private static final String DOC_CONTENT = "doc_content";
    private static final String MSG_TYPE = "msg_type";
    private static final String IS_SUCCESS = "is_success";//是否成功

    private String mUserId = "";

    public MessageDB(Context context) {
        PreferenceUtil mPreferenceUtil = PreferenceUtil.getInstance(context);
        mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        mUserId = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");

    }

    /**
     * 添加一个聊天消息到某张聊天表
     *
     * @param chatMsg
     */
    public void addChatMessage(ChatMoreMsg chatMsg) {
        String chatGroupId = chatMsg.getChatGroupID();
        createMessageTable(chatGroupId);
        int count = 0;
        if (!StringUtil.isEmpty(chatMsg.getMsgID())) {
            String sql = "select count(*) as count from _" + chatGroupId + " where "
                    + MSG_ID + " = " + chatMsg.getMsgID();
            Cursor cursor = mDb.rawQuery(sql, null);
            if (cursor.moveToNext())
                count = cursor.getInt(cursor.getColumnIndex("count"));
            cursor.close();
        }
        if (count == 0) {
            int isReaded = chatMsg.isReaded() ? 1 : 0;
            int isSuccess = chatMsg.isSuccess() ? 1 : 0;
            mDb.execSQL(
                    "insert into _" + chatGroupId + " (" + MSG_ID + "," + SENDER_ID + "," + SENDER_NAME
                            + "," + SENDER_IMG + "," + SEND_TIME + "," + IS_READED + "," + TEXT_CONTENT + ","
                            + IMG_CONTENT + "," + IMG_THUMBNAILS + "," + VOICE_CONTENT + "," + DOC_CONTENT + "," + MSG_TYPE + "," + IS_SUCCESS
                            + ") values(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[]{chatMsg.getMsgID(), chatMsg.getSenderID(),
                            chatMsg.getSenderName(), chatMsg.getSenderImg(), chatMsg.getSendTime(), isReaded,
                            chatMsg.getTextContent(), chatMsg.getImageContent(), chatMsg.getImageThumbnails(), chatMsg.getVoiceContent(), chatMsg.getDocContent(), chatMsg.getMsgType(), isSuccess});

        }
    }


    /**
     * 查询某张聊天表中的部分数据(暂时注释了分页逻辑,查询的是全部信息，若需加入分页，启用注释掉的sql语句，然后在lsitview中加入相关逻辑)
     *
     * @param chatGroupID groupId
     * @param currentPage 当前页码
     * @param pageSize    每页的个数
     * @return
     */
    public ArrayList<ChatMoreMsg> findMessagesByChatGroupId(String chatGroupID, String useId, int currentPage, int pageSize) {
        createMessageTable(chatGroupID);
        ArrayList<ChatMoreMsg> chatMsgs = new ArrayList<ChatMoreMsg>();
        int start = (currentPage - 1) * pageSize;
        int end = start + pageSize;
        /*String sql = "select * from _" + chatGroupID + " where " + SENDER_ID + " = " + useId + " and "+ IS_COMMING + " = 0 or "+SENDER_ID + " != " + useId + " and "+ IS_COMMING + " = 1" + " order by send_time desc limit  "
                + start + " , " + end;*/
        String sql = "select * from _" + chatGroupID + " order by send_time desc limit " + start + " , " + end;
//        String sql = "select * from _" + chatGroupID + " order by _id  desc ";

        Cursor cursor = mDb.rawQuery(sql, null);
        ChatMoreMsg chatMsg = null;
        while (cursor.moveToNext()) {
            String msgId = cursor.getString(cursor.getColumnIndex(MSG_ID));
            String senderId = cursor.getString(cursor.getColumnIndex(SENDER_ID));
            String senderName = cursor.getString(cursor.getColumnIndex(SENDER_NAME));
            String senderImg = cursor.getString(cursor.getColumnIndex(SENDER_IMG));
            String sendTime = cursor.getString(cursor.getColumnIndex(SEND_TIME));
            int isReaded = cursor.getInt(cursor.getColumnIndex(IS_READED));
            String textContent = cursor.getString(cursor.getColumnIndex(TEXT_CONTENT));
            String imageContent = cursor.getString(cursor.getColumnIndex(IMG_CONTENT));
            String imageThumbnails = cursor.getString(cursor.getColumnIndex(IMG_THUMBNAILS));
            String voiceContent = cursor.getString(cursor.getColumnIndex(VOICE_CONTENT));
            String docContent = cursor.getString(cursor.getColumnIndex(DOC_CONTENT));
            int msgType = cursor.getInt(cursor.getColumnIndex(MSG_TYPE));
            int isSuccess = cursor.getInt(cursor.getColumnIndex(IS_SUCCESS));
            chatMsg = new ChatMoreMsg(msgType, "", sendTime, msgId, senderId, senderName, senderImg, chatGroupID, isReaded == 1, textContent, imageContent, imageThumbnails, voiceContent, docContent, isSuccess == 1);
            chatMsgs.add(chatMsg);
        }
        Collections.reverse(chatMsgs);//反向顺序返回list
        cursor.close();
        return chatMsgs;
    }

    /**
     * 统计某一张聊天信息表中的未读消息数
     *
     * @param chatGroupId
     * @return
     */
    public int getUnReadCountOfOneGroup(String chatGroupId) {
        createMessageTable(chatGroupId);
//        String sql = "select count(*) as count from _" + chatGroupId + " where "
//                + IS_COMMING + " = 1 and " + IS_READED + " = 0";
        String sql = "select count(*) as count from _" + chatGroupId + " where "
                + SENDER_ID + " != " + mUserId + " and " + IS_READED + " = 0";
        Cursor cursor = mDb.rawQuery(sql, null);
        int count = 0;
        if (cursor.moveToNext())
            count = cursor.getInt(cursor.getColumnIndex("count"));
        cursor.close();
        return count;
    }

    /**
     * 统计所有聊天信息表中的未读消息
     *
     * @param groupIds 元素为groupId的list集合
     * @return
     */
    public int getUnReadCountOfAllGroup(List<String> groupIds) {
        int count = 0;
        for (String groupId : groupIds) {
            count += getUnReadCountOfOneGroup(groupId);
        }
        return count;
    }

    /**
     * 将某张聊天表的所有消息置为已读状态
     *
     * @param chatGroupID
     */
    public void updateAllMsgReaded(String chatGroupID) {
        createMessageTable(chatGroupID);
        mDb.execSQL("update _" + chatGroupID + " set " + IS_READED + " = 1 where " + IS_READED + " = 0 "
                , new Object[]{});
    }


    public void updateMessageStatus(String chatGroupID, String msgTime, ChatMoreMsg chatMoreMsg) {
        int isSuccess=chatMoreMsg.isSuccess() ? 1 : 0;
        createMessageTable(chatGroupID);
        try {
            mDb.execSQL("update _" + chatGroupID + " set " + MSG_ID + " = " + chatMoreMsg.getMsgID() + " , " + IS_SUCCESS + " = "+ isSuccess + " where " + MSG_ID + " = " + msgTime
                    , new Object[]{});
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 删除某张表下的所有消息，用于清除聊天记录
     *
     * @param groupId
     */
    public int deleteMessagesByGroudID(String groupId) {
        return mDb.delete("_" + groupId, null, null);
    }

    /**
     * 删除某张表下的某条消息
     *
     * @param groupId
     */
    public int deleteOneMsgByGroudID(String groupId, String msgId) {
        return mDb.delete("_" + groupId, MSG_ID + " = ? ", new String[]{msgId});
    }

    /**
     * 创建一张表名为聊天组ID的聊天消息表
     *
     * @param chatGroupId
     */
    private void createMessageTable(String chatGroupId) {
        mDb.execSQL("CREATE table IF NOT EXISTS _" + chatGroupId
                        + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + MSG_ID + " TEXT, "
                        + SENDER_ID + " TEXT, "
                        + SENDER_NAME + " TEXT, "
                        + SENDER_IMG + " TEXT, "
                        + SEND_TIME + " TEXT, "
                        + IS_READED + " integer, "
                        + IS_SUCCESS + " integer, "
                        + TEXT_CONTENT + " TEXT, "
                        + IMG_CONTENT + " TEXT, "
                        + IMG_THUMBNAILS + " TEXT, "
                        + VOICE_CONTENT + " TEXT, "
                        + DOC_CONTENT + " TEXT, "
                        + MSG_TYPE + " integer ); "

        );
    }

}
